package com.cjk.foundation.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipUtil {
	
	public static void makeZip(String zipFileName, String sourceFileName) {
		try {
			ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(zipFileName));
			BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(zipOutputStream);
			File sourceFile = new File(sourceFileName);
			File[] files = sourceFile.listFiles();
			for (int i = 0; i < files.length; i++) {
				compress(zipOutputStream, bufferedOutputStream, files[i], files[i].getName());
			}
			zipOutputStream.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private static void compress(ZipOutputStream zipOutputStream, BufferedOutputStream bufferedOutputStream, File sourceFile, String base) {
		try {
			if (sourceFile.isDirectory()) {
				File[] files = sourceFile.listFiles();
				if (files.length == 0) {
					zipOutputStream.putNextEntry(new ZipEntry(base));
				} else {
					for (int i = 0; i < files.length; i++) {
						compress(zipOutputStream, bufferedOutputStream, files[i], base + "/" + files[i].getName());
					}
				}
			} else {
				zipOutputStream.putNextEntry(new ZipEntry(base));
				FileInputStream fileInputStream = new FileInputStream(sourceFile);
				BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
				int tag;
				while ((tag = bufferedInputStream.read()) != -1) {
					zipOutputStream.write(tag);			
				}
				bufferedInputStream.close();
				fileInputStream.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
//	public static void main(String[] args) {
//		makeZip("D:\\电影.zip", "F:\\电影");
//	}
}
